<template>
    <div id="chat-room">
      <!-- 结果页 -->
      <audio id="layer-music" src="http://www.h5feel.com/addons/tianji_xmluma/template/static/music.mp3" preload="true" loop></audio>
      <div class="result position" v-if="scen.result">
        <div class="res res-save position" :class="activeBg.bg">
          <div class="frame" :class="activeBg.people">
            <div class="people" >
              <img :src="img.people2" alt="" />
              <img :src="img.imgUrl" alt="" />
            </div>
            <div class="index" :class="activeBg.index"><i>99</i></div>
            <div class="QR">
              <img :src="img.QR" alt="" />
              <p>扫描二维码合影</p>
            </div>
          </div>
        </div>
        <div class="res position" :class="activeBg.bg">
          <div class="frame" :class="activeBg.people">
            <div class="people" >
              <img :src="img.people2" alt="" />
              <img :src="img.imgUrl" alt="" />
            </div>
            <div class="index" :class="activeBg.index"><i>99</i></div>
          </div>
        </div>
        <div class="save position">
          <img src="" alt=""/>

        </div>
        <section class="res-btn">

          <p></p>

          <img src="" alt="" style="    opacity: 0.01; position: absolute;bottom: 2rem;width: 100%;left: 0rem;"/>

          <div class="btn" style="line-height: 0">

            <router-link to="" @click.native="Comeback">重新上传</router-link>

            <router-link to="">下载</router-link>

          </div>

        </section>
        <section id="canvas" class="position"></section>
      </div>
      <!-- 上传图片 -->
      <div class="Filename position" :class="activeBg.bg" v-if="scen.Filename">
        <div class="tab-style">
          <span class="v-active" @touchstart="tabStyle">风格1</span>
          <span @touchstart="tabStyle">风格2</span>
          <span @touchstart="tabStyle">风格3</span>
        </div>
        <div class="people" :class="activeBg.people">
          <img :src="img.people" alt="" />
          <img :src="img.people1" alt=""  class="people1"/>
          <div class="index" :class="activeBg.index"></div>
          <div class="title"></div>
        </div>
        <div id="showmessage" style=" display: flex;display: -webkit-flex;align-items: center;ckground-color: rgba(0, 0, 0, 0.5);width: 100%;height: 100%;position: absolute;top: 0rem;left: 0rem;" @touchend="touchmessage">

              <div style="display: none;width: 8.96rem;height: auto;line-height: 0.59733333rem;font-size: 0.512rem;color: #c71585;padding: 0.64rem;border-radius: 0.17066667rem;-webkit-border-radius: 0.17066667rem;background-color: #fff;margin: 0 auto;margin-left: 3rem;"></div>

        </div>
        <div id="kuang" class="pulse animated">
        </div>
        <div class="upload">
            <button>
              上传图片
              <input type="file" value="" name="" ref="file" @touchend="touchend"/>
            </button>
        </div>
        <div class="file_load position" style="" v-if="submit.loading">
          <div><span style="color: white;font-size:0.65rem;text-align: center;margin-top: 2rem;display: block;">请耐心等待，正在努力制作中……</span></div>

          <section class="layer_text"></section>
        </div>
      </div>
      <!-- 提交预约信息 -->
      <div class="about position" v-if="scen.about">
        <div class="about-info">
          <div class="info-name">
            <p>您的姓名 <span v-show="layer.name">请输入您的姓名</span></p>
            <input type="text" value="" name="" />
          </div>
          <div class="info-sex">
            <p>性别</p>
            <select v-model='layer.sex' >
              <option value='1' selected="selected">男</option>
              <option value='2'>女</option>
            </select>
          </div>
          <div class="info-tel">
            <p>手机号码 <span v-show="layer.tel">{{layer.telText}}</span></p>
            <input type="tel" value="" name="" />
          </div>
          <button @touchstart="Submit">提交信息</button>
        </div>
        <div class="position" v-if="submit.onOff">
          <p>正在提交中.....</p>
        </div>
      </div>
      <!-- 模拟聊天 -->
      <div class="ChatRoom position" v-if="scen.ChatRoom">
        <swiper :options="swiperOption" ref="mySwiper">
          <swiper-slide class="room" v-html="roomHTML"></swiper-slide>
        </swiper>
        <section class="text-input">
          <input type="text" value="" name="" @focus="foucs" @blur="blur" /><span @touchstart="touchstart">发送</span>
        </section>
      </div>
    </div>
</template>

<script>
  let [timer,parStr,valnum] = [null,"",-1];
  let textArr = null;

  import people from "@/common/images/people2.png"
  import people2 from "@/common/images/people2.png"
  import QR from "@/common/images/QR.png"
  import bg11 from "@/common/images/people4.png"
  import people1 from "@/common/images/bb1.png"
  import rw1 from "@/common/images/bb1.png"
  import rw2 from "@/common/images/bb2.png"
  import rw3 from "@/common/images/bb3.png"
  import rw4 from "@/common/images/bg1.png"
  import rw5 from "@/common/images/bg2.png"
  import rw6 from "@/common/images/bg3.png"
  import rw7 from "@/common/images/gg1.png"
  import rw8 from "@/common/images/gg2.png"
  import rw9 from "@/common/images/gg3.png"
  import rw10 from "@/common/images/gb1.png"
  import rw11 from "@/common/images/gb2.png"
  import rw12 from "@/common/images/gb3.png"

  let rwarray = [rw1,rw2,rw3];
  let modelarray = ['youtu_76905_20180719104211_2366','youtu_76906_20180719104303_2367','youtu_76907_20180719104325_2368'];
  let kuang_x=[5,4.1,4.1];
  let kuang_y=[8.8,8.4,9]
  let model = "youtu_76905_20180719104211_2366";

  import html2canvas from "html2canvas"
    export default {
        name:"chat-room",
        data() {
            return {
              roomHTML:'',
              user:{
                user_img:null,
                user_name:null
              },
              //背景切换
              activeBg:{
                bg:"v-active-bg0",
                people:"v-frame0",
                index:"v-index0"
              },
              //提交预约信息提醒
              layer:{
                name:false,
                sex:1,
                tel:false,
                telText:null
              },
              submit:{
                onOff:false,
                loading:false,
                onHref:false
              },
              //上传图片合成模板
              img:{
                people,
                people1,
                people2,
                QR,
                bg11,
                imgUrl:null
              },
              //场景切换
              scen:{
                ChatRoom:true,
                about:false,
                Filename:false,
                result:false
              },
              html2canvas,
              //swiper滑屏相关配置
              swiperOption:{
                direction: 'vertical',
                slidesPerView: 'auto',
                freeMode: true,
                mousewheel: true,
                autoHeight : true
              }
            }
        },
        created() {},
        computed:{
          store(){
            return this.$store.state;
          },
          mySwiper() {
            return this.$refs.mySwiper.swiper;
          }
        },
        mounted() {

          this.$http.get("http://www.h5feel.com/app/index.php?i=26&c=utility&a=userinfo&isajax=true",{
            withCredentials:true
          }).then((response)=>{
              if(response.data.code == 1001){
                  window.location.href = data.data.redirect_url+'&redirect_url='+window.location.href;
              }
            this.user.user_img = response.data.avatar;
            this.user.user_name = response.data.nickname;

            this.roomHTML = '';

            this.store.getCookie('name') === "杨紫"?textArr = [
              /*杨紫*/
              "有没有看我主演的《天乩之白蛇传说》~",
              "这部剧真的很不错哦。我最近即将新官儿上任，成为《天乩之白蛇传说》同名手游里的首席设计官，并且亲手设计了一套游戏时装想邀请你试穿一下，不知道你方不方便呐？",
              "哈哈，果然是自乩人，不如留个电话给我，我教你如果到游戏中体验我设计的时装吧。",
              "必须得合影留念啊，<br /><em>快来点击和我合影吧</em><img src='http://www.h5feel.com/addons/tianji_xmluma/template/static/share_logo.png' alt='合影图片'>"
            ]:textArr = [
              /*邓伦*/
              "有没有看我主演的《天乩之白蛇传说》~",
              "这部剧真的很不错哦。我最近即将新官儿上任，成为《天乩之白蛇传说》同名手游里的首席设计官，并且亲手准备了一项神秘服务想请你体验，不知道你方不方便呐？",
              "哈哈，果然是自乩人，不如留个电话给我，我教你如何体验这项神秘服务吧。",
              "必须得合影留念啊，<br /><em>快来点击和我合影吧</em><img src='http://www.h5feel.com/addons/tianji_xmluma/template/static/share_logo.png' alt='合影图片'>"
            ];

            clearInterval(timer);

            let name = this.store.getCookie('code') == 0?"杨紫":"任嘉伦";
            this.getData( "hello "+this.user.user_name+"，我是"+name+"！你总算通过我的好友申请啦~");

            timer = setInterval(() => {
              valnum++;

              if (valnum >= textArr.length) valnum = textArr.length-1;
              this.getData(textArr[valnum]);
              let roomH = $(".room").outerHeight(true);
              let swiperH = $(".ChatRoom").find(".swiper-container").outerHeight(true);
              let lastChildren = $(".room .roomChildren:last-child").outerHeight(true);
              if (roomH >= swiperH){this.mySwiper.setTranslate(swiperH - (roomH+lastChildren));}

              setTimeout(() => {
                let roomH = $(".room").outerHeight(true);
                let swiperH = $(".ChatRoom").find(".swiper-container").outerHeight(true);
                let lastChildren = $(".room .roomChildren:last-child").outerHeight(true);
                if (roomH >= swiperH){this.mySwiper.setTranslate(swiperH - (roomH+lastChildren));}
              },20);

            },300000);
          }).catch((error) => {
          });


        },
        methods:{
          getData(text) {
            let PW = '';
            if (text === textArr[textArr.length-1]){
              let _this = this;
              PW = 100+"%";

              $(".room").on("touchstart",".left",function (){
                  let layerMusic = document.querySelector("#layer-music");
                  layerMusic.play();
                _this.scen.ChatRoom = false;
                _this.scen.about = true;
                clearInterval(timer);
              });

            }

            parStr += `<div class="left roomChildren">

              <img src="${this.store.getCookie('headImg')}" alt="" />

              <div>

                <p style="width:${PW};">${text} <span></span></p>

              </div>

            </div>`;
            this.roomHTML = parStr;
          },
          touchmessage(){
              $('#showmessage').hide();
              $('#showmessage div').hide();
          },
          getLoadingLayer(text) {
            $(".file_load div").hide(0,function (){

              $(".file_load .layer_text").text(text).show();

            });
            setTimeout(() => {

              this.submit.loading = false;

              $(".file_load div").show(0,function (){
              });
            },2000);
          },
          //模拟聊天生成dome节点
          touchstart() {
            let val = $(".text-input input").val();

            if (val === "")return false;

            clearInterval(timer);
            parStr += `<div class="right roomChildren">

            <img src="${this.user.user_img}" alt="" />

            <div>

              <p>${val} <span></span></p>

            </div>

          </div>`;
            this.roomHTML = parStr;
            $(".text-input input").val('');

            setTimeout(() => {
              let roomH = $(".room").outerHeight(true);
              let swiperH = $(".ChatRoom").find(".swiper-container").outerHeight(true);
              let lastChildren = $(".room .roomChildren:last-child").outerHeight(true);
              if (roomH >= swiperH){this.mySwiper.setTranslate(swiperH - (roomH+lastChildren));}

            },20);
            valnum++;
            // console.log(valnum)
            if(valnum==4){
              this.scen.ChatRoom = false;
              this.scen.about = true;
              console.log(this.scen.about)
            }

            if (valnum >= textArr.length){valnum = textArr.length-1;}

            setTimeout(() => {
              this.getData(textArr[valnum]);
              this.roomHTML = parStr;
              setTimeout(() => {
                let roomH = $(".room").outerHeight(true);
                let swiperH = $(".ChatRoom").find(".swiper-container").outerHeight(true);
                let lastChildren_2 = $(".room .roomChildren:last-child").outerHeight(true);
                if (roomH >= swiperH){this.mySwiper.setTranslate(swiperH - (roomH+lastChildren_2));}
              },20);

            },20);

          },
          //上传图片转成base64格式
          touchend() {
            let File = this.$refs.file;
            let reader = new FileReader();
            let Http = this.$http;
            let _this = this;
            $(File).on("change",function (){
                if(File.files[0].size >= '8388608'){
                 $('#showmessage').show();
                 $('#showmessage div').html('图片不能大于8M，请重新上传').show();
                    setTimeout(() => {
                        $('#showmessage').hide();
                        $('#showmessage div').hide();
                    },3000);
                 return;
                }
              reader.readAsDataURL(File.files[0]);
              reader.onload = function (){
                  let lindex =  layer.open({
                      type: 2 ,
                      content:'请耐心等待，正在努力制作中……'
                  });
                // _this.submit.loading = true;
                Http.post("http://www.h5feel.com/app/index.php?i=26&c=entry&do=baseupload&m=tianji_xmluma&isajax=true",{
                  reg_img:reader.result,
                  withCredentials:true
                }).then((response) => {
                  $(File).val("");
                  if(response.data.code == 1){
                    console.log(response.data.data)
                    Http.post("http://www.h5feel.com/app/index.php?i=26&c=entry&do=api&m=tianji_xmluma&isajax=true",{
                      img:response.data.data + '?imageslim',
                      sex:1,
                      model_id:model,
                      withCredentials:true
                    }).then((response) => {
                      if(response.data){
                        // console.log(response.data.code)
                        if(response.data.code == '0'){
                          _this.scen.Filename = false;
                          _this.scen.result = true;
                          // console.log(response.data.base)
                          _this.img.imgUrl = response.data.base;
                          //dom渲染完成执行的函数
                          _this.$nextTick(function () {
                              html2canvas(document.querySelector(".res-save")).then(function(canvas) {
                                //将元素转化为canvas
                                document.querySelector("#canvas").appendChild(canvas);
                                console.log(canvas.toDataURL('image/jpeg'));
                                //将canvas转化为image
                                $(".save img").get(0).src = canvas.toDataURL('image/jpeg');
                                $(".res-btn img").get(0).src = canvas.toDataURL('image/jpeg');
                              });
                            });
                        }else if(response.data.code == '1000'){
                          _this.getLoadingLayer('请上传有人脸的图片');
                        }else if(response.data.code == '-1008'){
                          _this.getLoadingLayer('人脸检测失败');
                        }else {
                          _this.getLoadingLayer('参数错误，请重试');
                        }
                      }else {
                        _this.getLoadingLayer('求异常，请重试！');
                      }
                      layer.close(lindex);
                    }).catch((error) => {
                      _this.getLoadingLayer('网络异常，请重试！');
                        layer.close(lindex);
                    }).finally((e) => {
                      _this.submit.loading = false;

                    });
                 }
                }).catch((error) => {
                });

              }
            });
          },
          Submit() {
            let [name,sex,tel] = [$(".info-name input").val(),this.layer.sex,$(".info-tel input").val()];
            let regu = "^[ ]+$";//空格的正则
            let re = new RegExp(regu);
            let myreg = "^[1][3,4,5,7,8,9][0-9]{9}$";//电话号码正则
            let Telre = new RegExp(myreg);
            if (name === "" ||re.test(name)){
              this.layer.name = true;
              setTimeout(() => {
                this.layer.name = false;
            },2000);
              return false;
            }
            if (sex === "" || re.test(sex)){
              this.layer.sex = true;
              setTimeout(() => {
                this.layer.sex = false;
            },2000);
              return false;
            }

            if (tel === "" || re.test(tel)){
              this.layer.tel = true;
              this.layer.telText = "请输入您的手机号码";
              setTimeout(() => {
                this.layer.tel = false;
                this.layer.telText = "";
            },2000);

              return false;
            }

            if (tel.length != 11){
              this.layer.tel = true;
              this.layer.telText = "您输入的手机号位数不正确";

              setTimeout(() => {
                this.layer.tel = false;
              this.layer.telText = "";
            },2000);
            }

            if (!Telre.test(tel)){
              this.layer.tel = true;
              this.layer.telText = "请输入正确的手机号";

              setTimeout(() => {
                this.layer.tel = false;
                this.layer.telText = "";
            },2000);
              return false;
            }

            this.submit.onOff = true;


            this.$http.post("http://www.h5feel.com/app/index.php?i=26&c=entry&do=api&m=tianji_xmluma&act=order&isajax=true",{
              username:name,//用户名
              mobile:tel,//电话
              sex:sex,//性别
              withCredentials:true
            }).then((response)=>{
            this.submit.onOff = false;
            this.scen.about = false;
            this.scen.Filename = true;
            this.kuang();
            this.model();
          }).catch((error) => {
          });

          },
          kuang(){
              setInterval(() => {
                  $("#kuang").removeClass("pulse animated");
                  setTimeout(() => {
                      $("#kuang").addClass("pulse animated");
                  },1250)

              },2500);
          },

          model(){
                $(".model1").scc=({"margin-top":"0.1rem",
                    "border": "0.2rem solid #ffffff"})
                let code = this.$store.state.getCookie('code');
                var sex = this.layer.sex;
                //明星为杨紫
                if(code == 0){
                    this.img.people = this.img.bg11;
                    this.img.people2 = this.img.bg11;
                    if(sex == 1){
                        rwarray = [rw10,rw11,rw12];
                        modelarray = ['youtu_76912_20180719104617_2374','youtu_76913_20180719104642_2375','youtu_76914_20180719104706_2376'];
                        kuang_x=[4.65,4.25,4.35];
                        kuang_y=[8.65,8.55,9.15]
                        $('#kuang').css('top',kuang_x[0]);
                        $('#kuang').css('left',kuang_y[0]);
                        model = modelarray['0'];
                    }else{
                        rwarray = [rw7,rw8,rw9];
                        modelarray = ['youtu_76915_20180719104729_2377','youtu_76916_20180719104801_2378','youtu_76917_20180719104819_2379'];
                        kuang_x=[5.65,5.15,5.15];
                        kuang_y=[9.65,8.45,9.05];
                        $('#kuang').css('top',kuang_x[0]);
                        $('#kuang').css('left',kuang_y[0]);
                        model = modelarray['0'];
                        this.img.people1 = rwarray[0];
                    }
                }
                else{
                    if(sex == 1){
                        rwarray = [rw1,rw2,rw3];
                        modelarray = ['youtu_76905_20180719104211_2366','youtu_76906_20180719104303_2367','youtu_76907_20180719104325_2368'];
                        kuang_x=[5.15,5.15,5.15];
                        kuang_y=[8.95,9.05,9.05];
                        $('#kuang').css('top',kuang_x[0]);
                        $('#kuang').css('left',kuang_y[0]);
                        model = modelarray['0'];
                    }else{
                        rwarray = [rw4,rw5,rw6];
                        modelarray = ['youtu_76908_20180719104347_2369','youtu_76909_20180719104408_2370','youtu_76911_20180719104552_2373'];
                        kuang_x=[6.25,5.95,5.95];
                        kuang_y=[9.15,8.55,9.45];
                        $('#kuang').css('top',kuang_x[0]);
                        $('#kuang').css('left',kuang_y[0]);
                        model = modelarray['0'];
                        this.img.people1 = rwarray[0];
                    }
                }

            },
          //获取焦点清除定时器
          foucs() {
            clearInterval(timer);
            $(".text-input").css({"margin-top":-1.1+"rem"});
            var timer2=null;
            var index = 0;
            clearInterval(timer2);
            timer2 = setInterval(function() {
              if(index>5) {
                $('body').scrollTop(1000000);
                clearInterval(timer2);
              }
              index++;
            }, 50)
            // alert($('body').scrollTop())

          },
          //失去焦点开启开启自动聊天
          blur() {

            $(".text-input").css({"margin-top":0});
            // $(".text-input").css({"bottom":0});
            $('body').scrollTop(0);
            timer = setInterval(() => {
              valnum++;
              if (valnum >= textArr.length){valnum = textArr.length-1;}
              this.getData(textArr[valnum]);
              setTimeout(() => {
                let roomH = $(".room").outerHeight(true);
                let swiperH = $(".ChatRoom").find(".swiper-container").outerHeight(true);
                let lastChildren = $(".room .roomChildren:last-child").outerHeight(true);

                if (roomH >= swiperH){this.mySwiper.setTranslate(swiperH - (roomH+lastChildren));}
              },20)

            },6000000);
          },
          //重新上传照片
          Comeback() {
            this.scen.result = false;
            this.scen.Filename = true;
            this.submit.loading = false;
            this.activeBg = {
              bg:"v-active-bg0",
              people:"v-frame0",
              index:"v-index0"
            };
            this.img.people1 = rwarray[0];
            model = modelarray[0];
          },
          //切换背景
          tabStyle(tag) {
            let _index = $(tag.target).index();

            $(".tab-style span").each(function (i,elem){
              $(elem).removeClass('v-active');
            });
            $(".tab-style span").eq(_index).addClass('v-active');
            this.activeBg = {
              bg:"v-active-bg"+_index,
              people:"v-frame"+_index,
              index:"v-index"+_index,
            };
              $('#kuang').css('top',kuang_x[_index]+'rem');
              $('#kuang').css('left',kuang_y[_index]+'rem');
            this.img.people1 = rwarray[_index];
            model = modelarray[_index];
          }
        }
    }
</script>
<style>


  @-webkit-keyframes pulse {
    from {
      -webkit-transform: scale3d(1, 1, 1);
      transform: scale3d(1, 1, 1);
    }

    50% {
      -webkit-transform: scale3d(1.3, 1.3, 1.3);
      transform: scale3d(1.3, 1.3, 1.3);
    }

    to {
      -webkit-transform: scale3d(1, 1, 1);
      transform: scale3d(1, 1, 1);
    }
  }

  @keyframes pulse {
    from {
      -webkit-transform: scale3d(1, 1, 1);
      transform: scale3d(1, 1, 1);
    }

    50% {
      -webkit-transform: scale3d(1.3, 1.3, 1.3);
      transform: scale3d(1.3, 1.3, 1.3);
    }

    to {
      -webkit-transform: scale3d(1, 1, 1);
      transform: scale3d(1, 1, 1);
    }
  }

  .pulse {
    -webkit-animation-name: pulse;
    animation-name: pulse;
  }

  .animated {
    -webkit-animation-duration: 2s;
    animation-duration: 2s;
    -webkit-animation-fill-mode: both;
    animation-fill-mode: both;
  }
</style>
